<template>
  <div class="activity-content">
    <el-scrollbar>
      <div class="activity-cards">
        <template v-for="item in ACTIVITY_TYPE" :key="item.type">
          <el-card style="width: 300px">
            <div class="card-item">
              <div class="title">{{ item.title }}</div>
              <div class="dec">{{ item.dec }}</div>
              <div class="button">
                <el-button
                  type="primary"
                  v-hasPermi="['market:activity:add']"
                  plain
                  @click="handleAdd(item)"
                  >立即新建</el-button
                >
              </div>
            </div>
          </el-card>
        </template>
      </div>
    </el-scrollbar>
    <div class="activity-center">
      <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
        <el-form-item label="优惠券名称" prop="couponName">
          <el-input
            style="width: 200px"
            maxlength="16"
            v-model.trim="queryParams.couponName"
            placeholder="请输入优惠券名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="名称备注" prop="remark">
          <el-input
            style="width: 200px"
            maxlength="30"
            v-model.trim="queryParams.remark"
            placeholder="请输入名称备注"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="优惠券状态" prop="status">
          <el-select v-model="queryParams.status" fit-input-width clearable placeholder="请选择">
            <el-option label="全部状态" value=""></el-option>
            <el-option
              v-for="item in STATUS_OPTIONS"
              :key="item.status"
              :label="item.label"
              :value="item.status"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选择时间区间" prop="time">
          <el-date-picker
            style="width: 240px"
            v-model="queryParams.time"
            type="daterange"
            format="YYYY-MM-DD"
            value-format="x"
            :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
          />
        </el-form-item>
        <el-form-item label="优惠券类型" prop="type">
          <el-select v-model="queryParams.type" fit-input-width clearable placeholder="请选择">
            <el-option
              v-for="item in ACTIVITY_TYPE"
              :key="item.type"
              :label="item.title"
              :value="item.type"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="活动时间类型" prop="validDayType">
          <el-select
            v-model="queryParams.validDayType"
            fit-input-width
            clearable
            placeholder="请选择"
          >
            <el-option label="全部类型" :value="''"></el-option>
            <el-option label="固定时效" :value="1"></el-option>
            <el-option label="领取时效" :value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="城市标签" prop="cityName">
          <el-select
            v-model="queryParams.cityName"
            @change="handleQuery"
            fit-input-width
            placeholder="请选择"
          >
            <el-option
              v-hasPermi="['market:activity:national']"
              label="全国"
              value="全国"
            ></el-option>
            <el-option
              v-for="item in cityNameOptions"
              :key="item"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="resetQuery">重置</el-button>
          <el-button type="primary" @click="handleQuery">查询</el-button>
        </el-form-item>
      </el-form>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            v-hasPermi="['marketing:activity:extend']"
            type="primary"
            @click="handleExtend"
          >
            延长时间设置
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            v-hasPermi="['market:activity:grant']"
            type="primary"
            @click="handleBatchDistribute"
          >
            一键发放
          </el-button>
        </el-col>

        <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table ref="multipleTableRef" v-loading="loading" size="default" index :data="dataList">
        <el-table-column type="selection" :selectable="selectable" width="55" />
        <el-table-column
          label="优惠券名称"
          min-width="150px"
          align="center"
          show-overflow-tooltip
          prop="couponName"
        />
        <el-table-column
          label="创建时间"
          min-width="150px"
          align="center"
          show-overflow-tooltip
          prop="createTime"
        />
        <!-- TODO:活动时间 -->
        <!-- <el-table-column label="活动时间" width="165px" align="center">
          <template #default="{ row }">
            <div>
              {{ row.validStartTime ? row.validStartTime + '~\n' + row.validEndTime : '' }}
            </div>
          </template>
        </el-table-column> -->
        <el-table-column label="用券时间" width="165px" align="center">
          <template #default="{ row }">
            <div>
              {{ row.validStartTime ? row.validStartTime + '~\n' + row.validEndTime : '' }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="名称备注"
          min-width="120px"
          show-overflow-tooltip
          align="center"
          prop="remark"
        />
        <el-table-column label="城市标签" show-overflow-tooltip align="center" prop="cityName" />
        <el-table-column label="类型" width="100px" align="center" prop="type">
          <template #default="{ row }">
            <div>
              {{ getType(row.type) }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="优惠内容" width="150px" align="center" prop="details" />
        <!-- TODO:活动状态 -->
        <!-- <el-table-column label="活动状态" width="80px" align="center" prop="status">
          <template #default="{ row }">
            <div>
              <el-link :underline="false" :type="getStatusType(row.status)">{{
                getStatusLabel(row.status)
              }}</el-link>
            </div>
          </template>
        </el-table-column> -->
        <el-table-column label="状态" width="80px" align="center" prop="status">
          <template #default="{ row }">
            <div>
              <el-link :underline="false" :type="getStatusType(row.status)">{{
                getStatusLabel(row.status)
              }}</el-link>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="已领取" align="center" prop="neckNum">
          <template #default="{ row }">
            <div>
              <el-link
                :underline="false"
                type="primary"
                :disabled="!hasPermi(['market:activity:already'])"
                @click="handleList(row, '已领取')"
                >{{ row.neckNum }}</el-link
              >
            </div>
          </template>
        </el-table-column>
        <el-table-column label="剩余" align="center" prop="surplusCount" />
        <el-table-column label="已使用" align="center" prop="useNum" />
        <!-- <el-table-column label="用券总成交额(元)" width="130px" align="center" prop="turnover" />
        <el-table-column label="用券笔单价(元)" width="130px" align="center" prop="unitPrice" /> -->
        <el-table-column label="数据详情" align="center" width="80" fixed="right">
          <template #default="{ row }">
            <el-link
              v-hasPermi="['market:activity:statistic']"
              :underline="false"
              type="primary"
              @click="handleStatistic(row)"
              >查看</el-link
            >
          </template>
        </el-table-column>
        <el-table-column label="导出详情" align="center" width="80" fixed="right">
          <template #default="{ row }">
            <el-link
              v-hasPermi="['market:activity:exportDetails']"
              :underline="false"
              type="primary"
              @click="handleList(row, '导出详情')"
              >导出详情</el-link
            >
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" min-width="160" fixed="right">
          <template #default="{ row }">
            <div class="activity-actions">
              <el-link
                v-hasPermi="['market:activity:delete']"
                v-if="row.status === 2"
                style="margin-right: 6px"
                :underline="false"
                type="danger"
                @click="handleDelete(row)"
                >删除</el-link
              >
              <el-link
                v-hasPermi="['market:activity:expire']"
                v-if="row.status !== 2"
                style="margin-right: 6px"
                :underline="false"
                type="primary"
                @click="handleExpire(row)"
                >失效</el-link
              >
              <el-dropdown trigger="click" style="margin-right: 6px">
                <el-link
                  v-hasPermi="['market:activity:extension']"
                  :underline="false"
                  type="primary"
                  >推广</el-link
                >
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="getCouponLink(row.marketingId)"
                      ><span>分享口令</span>
                    </el-dropdown-item>
                    <el-dropdown trigger="click">
                      <el-button text :disabled="row.status === 2 || row.surplusCount <= 0" type=""
                        >发放优惠券</el-button
                      >
                      <template #dropdown>
                        <el-dropdown-item @click="handleDistribute(row.id)"
                          >批量发放</el-dropdown-item
                        >
                        <el-dropdown-item @click="handleDirectionalGrant(row.id)"
                          >定向发放</el-dropdown-item
                        >
                      </template>
                    </el-dropdown>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
              <!-- <el-link
                style="margin-right: 6px"
                :underline="false"
                type="primary"
                @click="handleMarket(row)"
                >推广设置</el-link
              > -->
              <el-link
                v-hasPermi="['market:activity:statistic']"
                style="margin-right: 6px"
                :underline="false"
                type="primary"
                @click="handleDetail(row)"
                >详情</el-link
              >
              <el-link
                v-hasPermi="['market:activity:statistic']"
                :disabled="row.surplusCount <= 0"
                style="margin-right: 6px"
                :underline="false"
                type="primary"
                @click="handleExport(row)"
                >导出</el-link
              >
              <!-- <el-link
                v-hasPermi="['market:activity:statistic']"
                :disabled="row.surplusCount <= 0"
                style="margin-right: 6px"
                :underline="false"
                type="primary"
                @click="handleDisabled(row)"
                >禁用</el-link
              > -->
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div style="margin-right: 10px">
        <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </div>
    </div>
    <el-dialog
      title="发放详情"
      v-model="dialogVisible"
      :align-center="true"
      class="activity-custom-dialog"
      width="500"
    >
      <el-scrollbar min-height="200px">
        <p
          v-for="(item, index) in couponList"
          style="margin-bottom: 10px; font-size: 16px"
          :key="index"
          >{{ item.name }}：已发送{{ item.count }}张优惠券</p
        >
      </el-scrollbar>
    </el-dialog>
    <!-- 新建 -->
    <addDialog ref="addRef" @refresh="handleQuery" :title="title" />
    <!-- 数据详情弹窗 -->
    <statisticDialog ref="statisticRef" />
    <!-- 已领取和导出详情 弹窗 -->
    <couponDialog ref="couponRef" :validStartTime="validStartTime" @close="getList" />
    <!-- 详情 -->
    <detailDialog ref="detailRef" :title="title" />
    <!-- 导出 -->
    <exportDialog @refresh="getList" ref="exportRef" />
    <!-- 延长时间 -->
    <extendDialog
      class="extendDialogBox"
      ref="extendRef"
      :selectionList="selectionList"
      @refresh="handleClose"
    />
    <!-- 推广设置弹窗 -->
    <!-- <marketSetting ref="marketRef" /> -->
    <!-- 已领取详情弹窗 -->
    <!-- <claimedDialog ref="claimedRef" /> -->
    <!-- 定向发放优惠券弹窗 -->
    <directionalGrant ref="directionalRef" @refresh="getList" />
  </div>
</template>

<script setup>
import statisticDialog from './cpts/statisticDialog.vue'
import couponDialog from './cpts/couponDialog.vue'
import detailDialog from './cpts/detailDialog.vue'
import addDialog from './cpts/addDialog.vue'
import exportDialog from './cpts/exportDialog.vue'
import extendDialog from './cpts/extendDialog.vue'
import directionalGrant from './cpts/directionalGrant.vue'

import {
  deleteActivityApi,
  distributeCouponApi,
  getCouponLinkApi,
  getCouponListApi
} from '@/api/marketing/activity/index'
import { listDataApi } from '@/api/system/dict/data'
import useGlobalStore from '@/store/modules/global'
import { hasPermi } from '@/utils/tools'
import { useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'

const route = useRoute()
const router = useRouter()
const globalStore = useGlobalStore()
const cityNameOptions = computed(() => {
  queryParams.cityName = globalStore.myCityList.length ? globalStore.myCityList[0] : ''
  return globalStore.myCityList
})
// =============== ==============

// TODO:状态新增已禁用
const STATUS_OPTIONS = [
  {
    label: '进行中',
    status: 1,
    type: 'success'
  },
  {
    label: '已失效',
    status: 2,
    type: 'info'
  },
  {
    label: '已过期',
    status: 3,
    type: 'info'
  },
  {
    label: '待开始',
    status: 4,
    type: 'warning'
  }
]
const ACTIVITY_TYPE = ref([])
const queryRef = ref(null)
const showSearch = ref(true)
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  couponName: '',
  remark: '',
  status: '',
  time: '',
  type: '',
  validDayType: '',
  cityName: ''
})

const total = ref(0)
const dataList = ref([])
const loading = ref(false)
const title = ref('')
// ================ format数据 ====================
const getListData = () => {
  listDataApi({ dictType: 'market_activity_type' }).then((res) => {
    ACTIVITY_TYPE.value = res?.rows.map((i) => {
      return {
        title: i.dictLabel,
        dec: i.remark,
        type: i.dictValue - 0
      }
    })
  })
}

function getType(type) {
  return ACTIVITY_TYPE.value.find((i) => {
    return i.type == type
  })?.title
}

function getStatusType(status) {
  return STATUS_OPTIONS.find((i) => {
    return i.status === status
  })?.type
}

// 获取value
function getStatusLabel(status) {
  return STATUS_OPTIONS.find((i) => {
    return i.status === status
  })?.label
}

// 新建
const addRef = ref(null)
function handleAdd(item) {
  title.value = item.title + '设置'
  addRef.value.init(item.type, queryParams.cityName)
}

// ================== 批量操作 ========================
const multipleTableRef = ref(null)
const selectionList = ref([])
const extendRef = ref(null)

function selectable(row) {
  if (row.status !== 2) {
    return true
  }
}
//延长时间 固定时效的券可以延长时间
function handleExtend() {
  if (!multipleTableRef.value.getSelectionRows().length) {
    return ElMessage({
      message: '请至少选择一个活动',
      type: 'error'
    })
  }
  const arr = multipleTableRef.value.getSelectionRows().filter((i) => {
    return !i.validStartTime
  })
  if (arr?.length) {
    ElMessage.error('抱歉，当前活动因规则限制，暂不支持延长领取时间哦~')
  }
  arr.forEach((row) => {
    // TODO: improvement typing when refactor table
    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    // @ts-expect-error
    multipleTableRef.value.toggleRowSelection(row, undefined)
  })
  // toggleRowSelection
  selectionList.value = multipleTableRef.value
    .getSelectionRows()
    .filter((i) => i.validStartTime)
    .map((i) => i.id)
  if (selectionList.value?.length) {
    extendRef.value.init()
  }
}

function handleClose() {
  multipleTableRef.value.clearSelection()
  getList()
}

// 批量发放
const dialogVisible = ref(false)
const couponList = ref([])
function handleBatchDistribute() {
  if (!multipleTableRef.value.getSelectionRows().length) {
    return ElMessage({
      message: '请至少选择一个活动',
      type: 'error'
    })
  }
  ElMessageBox.confirm('确定一键发放', '操作', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      const couponIds = multipleTableRef.value.getSelectionRows().map((i) => {
        return i.id
      })
      distributeCouponApi(couponIds).then((res) => {
        couponList.value = res?.data || []
        dialogVisible.value = true
        getList()
      })
    })
    .catch(() => {})
}

// ======================================

// 已领取和导出详情
const couponRef = ref(null)
const validStartTime = ref('')
function handleList(row, title) {
  validStartTime.value = row.validStartTime
  couponRef.value.init(row, title)
}

// 数据
const statisticRef = ref(null)
function handleStatistic(row) {
  statisticRef.value.init(row.couponName, row.id)
}

// 删除
function handleDelete(row) {
  ElMessageBox.confirm('活动记录将会被删除', '操作', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'error'
  })
    .then(() => {
      deleteActivityApi({ couponId: row.id, status: 0 }).then(() => {
        ElMessage({
          type: 'success',
          message: '操作成功'
        })
        handleQuery()
      })
    })
    .catch(() => {})
}
// 失效
function handleExpire(row) {
  ElMessageBox.confirm('活动将会被强制失效', '操作', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'error'
  })
    .then(() => {
      deleteActivityApi({ couponId: row.id, status: 2 }).then(() => {
        ElMessage({
          type: 'success',
          message: '操作成功'
        })
        getList()
      })
    })
    .catch(() => {})
}
/** 禁用 */
function handleDisabled(row) {
  ElMessageBox.confirm(`确定要禁用【 ${row?.couponName} 】吗？`, '操作', {
    confirmButtonText: '禁用',
    cancelButtonText: '取消',
    type: 'error'
  })
    .then(() => {})
    .catch(() => {})
}
/** 推广 */
const directionalRef = ref(null)
// 复制口令
function getCouponLink(marketingId) {
  getCouponLinkApi({ marketingId }).then((res) => {
    navigator.clipboard.writeText(res.data).then(() => {
      ElMessage({
        message: '复制口令成功',
        type: 'success'
      })
    })
  })
}
// 单张优惠券 批量发放优惠券
function handleDistribute(couponId) {
  ElMessageBox.confirm('是否一键发放', '操作', {
    confirmButtonText: '发放',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      distributeCouponApi([couponId]).then((res) => {
        couponList.value = res?.data || []
        dialogVisible.value = true
        getList()
      })
    })
    .catch(() => {})
}

// 单张优惠券 定向发放
function handleDirectionalGrant(couponId) {
  directionalRef.value.init(couponId)
}

// 推广设置
// const marketRef = ref(null)
// function handleMarket(row) {
//   marketRef.value.init()
// }

// 详情
const detailRef = ref(null)
function handleDetail(row) {
  title.value = getType(row.type) + '详情'
  addRef.value.init(row.type, queryParams.cityName, row.id)
}
// 导出
const exportRef = ref(null)
function handleExport(row) {
  exportRef.value.init(row)
}

// 禁用
function handleDisable(row) {
  const text = row.status === 1 ? '有活动关联此优惠券，是否强行禁止？' : '确定要禁用吗'
  ElMessageBox.confirm('是否禁用', '操作', {
    confirmButtonText: '禁用',
    cancelButtonText: '取消',
    type: 'error'
  }).then(() => {
    // TODO:禁用接口
    // disableCouponApi({ couponId: row.id, status: 2 }).then(() => {
    //   ElMessage({
    //     type: 'success',
    //     message: '操作成功'
    //   })
    // })
  })
}

// ======================= 搜索 ======================
function getList() {
  loading.value = false
  const params = {
    ...queryParams,
    validStartTime: queryParams.time?.length ? queryParams.time[0] : '',
    validEndTime: queryParams.time?.length ? queryParams.time[1] : ''
  }
  delete params.time
  getCouponListApi(params)
    .then((res) => {
      loading.value = false
      dataList.value = res?.data?.rows || []
      total.value = res?.data?.total || 0
    })
    .catch(() => {
      loading.value = false
      dataList.value = []
      total.value = 0
    })
}
// 搜索
function handleQuery() {
  queryParams.pageNum = 1
  getList()
}

// 重置
function resetQuery() {
  queryParams.id = ''
  queryRef.value.resetFields()
  handleQuery()
}

onMounted(() => {
  queryParams.cityName = globalStore.myCityList.length ? globalStore.myCityList[0] : ''
  console.log('路径参数', route.query)
  if (route.query.id) {
    queryParams.id = route.query.id
    queryParams.couponName = route.query.couponName
    queryParams.cityName = route.query.cityName
  }
  getListData()
  getList()
})
</script>

<style lang="scss" scoped>
@import './index.css';
</style>
